package com.eascs.gaczcontract.controller;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.internal.entity.PubDditem;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandService;
import com.eascs.admin.o2o.internal.service.PubDditemService;
import com.eascs.admin.o2o.internal.util.MoneyUtil;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.common.doc.pdf.PdfBuilder;
import com.eascs.common.doc.word.WordBuilder;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.nsEditDetail.entity.O2oMainShopInfoEntity;
import com.eascs.crm.nsEditDetail.service.CustomerShopInfoService;
import com.eascs.crm.nsEditDetail.service.IMainShopInfoService;
import com.eascs.gaczcontract.entity.CustomerBasicInfo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.workflow.common.service.sys.SysOrgService;

@Controller
public class SPDBGZContractRestContorller extends BaseRestController {
	@Autowired
	private O2oLoanapplyService loanService;
	@Autowired
	private O2oLoanUserService loanUserService;
	@Autowired
	LoanapplyExpandService loanapplyExpandService;
	@Autowired
	PubDditemService pubDditemService;
	@Reference
	SysOrgService sysOrgService;
	@Autowired
	CustomerShopInfoService shopInfoService;
	@Autowired
	private O2oPubDdItemService o2oPubDdItemService;
	@Reference
	IMainShopInfoService mainShopInfoService;
	
	@RequestMapping(value = "/toDownloadSPDBGZ")
	public BaseRestResult<String> checkShopInfo(String loanapplyNo) {
		return BaseRestResult.info("正在下载中...").andRedirect("/downloadSPDBGZContract?loanapplyNo=" + loanapplyNo);
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               浦发广州分行 带数据合同
	 *               </p>
	 */
	@RequestMapping(value = "/toDownloadSPDBGZ_PF")
	public BaseRestResult<String> toDownloadSPDBGZPF(String loanapplyNo) {
		return BaseRestResult.info("正在下载中...").andRedirect("/downloadSPDBGZContract_pf_word?loanapplyNo=" + loanapplyNo);
	}

	@RequestMapping(value = "/downloadSPDBGZContract", method = RequestMethod.GET)
	public void downloadJXContract(HttpServletResponse httpServletResponse, HttpServletRequest request,
			String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		if (loanapply == null) {
			return;
		}
		// 最后需要生产的模板文件
		String[] classPathFiles = { "/pdfTemplate/pfgz/db.pdf", "/pdfTemplate/pfgz/db.pdf","/pdfTemplate/pfgz/db.pdf",
				"/pdfTemplate/pfgz/hzxy.pdf", "/pdfTemplate/pfgz/hzxy.pdf" };

		Map<String, Object> data = fillData(loanapplyNo);

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		try {
			PdfBuilder.mergePdfFilesAndBuild(classPathFiles, data, outputStream);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		OutputStream os = null;
		try {
			String outfile = "";
			outfile = "浦发广州银行带数据合同.pdf";
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
				outfile = URLEncoder.encode(outfile, "UTF-8");
			} else {
				outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
			}
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setContentType("application/pdf");
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			os.write(outputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}

	@RequestMapping(value = "/toDownloadSPDBGZ_zl")
	public BaseRestResult<String> downloadSPDBGZContract_word_zl(String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		if(loanapply.getReceiveBank()==null||loanapply.getBankAccount()==null){
			return BaseRestResult.warn("请先保存开户银行和银行卡号!");
		}
		return BaseRestResult.info("正在下载中...").andRedirect("/downloadSPDBGZContract_word?loanapplyNo=" + loanapplyNo);
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               浦发广州分行 带数据合同
	 *               </p>
	 */
	@RequestMapping(value = "/downloadSPDBGZContract_pf_word", method = RequestMethod.GET)
	public void downloadSPDBGZContract_pf_word(HttpServletResponse httpServletResponse, HttpServletRequest request,
			String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		if (loanapply == null) {
			return;
		}
		// 最后需要生产的模板文件
		String classPathFiles = "/wordTemplate/pfyhhtdy.xml";
		Map<String, Object> data = fillZLData(loanapplyNo);
		OutputStream os = null;
		try {
			String outfile = "";
			outfile = "浦发银行带数据合同.doc";
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
				outfile = URLEncoder.encode(outfile, "UTF-8");
			} else {
				outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
			}
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setContentType("application/doc");
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			WordBuilder.buildDocFromXml(os, data, classPathFiles);
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
	
	@RequestMapping(value = "/downloadSPDBGZContract_word", method = RequestMethod.GET)
	public void downloadSPDBGZContract_word(HttpServletResponse httpServletResponse, HttpServletRequest request,
			String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		if (loanapply == null) {
			return;
		}
		// 最后需要生产的模板文件
		String classPathFiles = "/wordTemplate/zlyhdsjht.xml";
		Map<String, Object> data = fillZLData(loanapplyNo);
		OutputStream os = null;
		try {
			String outfile = "";
			outfile = "中旅银行带数据合同.doc";
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
				outfile = URLEncoder.encode(outfile, "UTF-8");
			} else {
				outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
			}
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setContentType("application/doc");
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			WordBuilder.buildDocFromXml(os, data, classPathFiles);
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
	
	private Map<String, Object> fillData(String loanapplyNo) {
		Map<String, Object> data = new HashMap<>();
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		NumberFormat nf = new DecimalFormat(",###.00");
		if (loanapply == null) {
			return data;
		}
		
		O2oLoanUserEntity loanUserEntity = loanUserService.findById(loanapply.getLoanId(), loanapplyNo);
		CustomerBasicInfo customerBasicInfo = loanService.getCustomerEntityById(loanUserEntity.getId());
		O2oLoanUserEntity loanSpouseUserEntity = loanUserService.findSpouseId(loanUserEntity.getLoanId(), loanapplyNo);
		List<O2oLoanUserEntity> guarantorByGuaraList = loanUserService.queryDBsById(loanapplyNo);
		O2oLoanUserEntity guarantorByGuara = null;

		if (guarantorByGuaraList != null && guarantorByGuaraList.size() > 0) {
			if (loanSpouseUserEntity == null && guarantorByGuaraList.size() > 2) {
				guarantorByGuara = guarantorByGuaraList.get(1);
			} else if (loanSpouseUserEntity != null) {
				guarantorByGuara = guarantorByGuaraList.get(0);
			}
			if (guarantorByGuara != null) {
				data.put("guarByGuara", guarantorByGuara.getUserFullName());// 担保人(用于责任担保书-第三方担保人版)
				data.put("guarIdCardByGuara", guarantorByGuara.getDocumentNo());// 担保人身份证(用于责任担保书-第三方担保人版)
				data.put("guarMobileByGuara", guarantorByGuara.getUserPhone());// 担保人电话号码(用于责任担保书-第三方担保人版)
				CustomerBasicInfo guaraExp = loanService.getCustomerEntityById(guarantorByGuara.getId());
				if (null != guaraExp) {
					String guaraacountAdress = getCountAdress(guaraExp);
					data.put("guarAcountAdress", guaraacountAdress);// 户口地址
				}
			}
		} else {
			data.put("guarByGuara", "");// 担保人
			data.put("guarIdCardByGuara", "");// 担保人身份证
		}

		if (loanSpouseUserEntity != null) {
			data.put("mateName", loanSpouseUserEntity.getUserFullName());// 配偶
			data.put("mateIdCard", loanSpouseUserEntity.getDocumentNo());// 配偶身份证
			data.put("mateMobile", loanSpouseUserEntity.getUserPhone());// 配偶手机号
			CustomerBasicInfo mateBasicInfo = loanService.getCustomerEntityById(loanSpouseUserEntity.getId());
			if (mateBasicInfo != null) {
				String acountAdress = getCountAdress(mateBasicInfo);
				data.put("mateAcountAdress", acountAdress);// 户口地址
			}
		} else {
			if (guarantorByGuaraList != null && guarantorByGuaraList.size() > 0) {
				guarantorByGuara = guarantorByGuaraList.get(0);
				if (guarantorByGuara != null) {
					data.put("mateName", guarantorByGuara.getUserFullName());// 担保人
					data.put("mateIdCard", guarantorByGuara.getDocumentNo());// 担保人身份证
					data.put("mateMobile", guarantorByGuara.getUserPhone());// 担保人手机号
					CustomerBasicInfo guaraExp = loanService.getCustomerEntityById(guarantorByGuara.getId());
					if (null != guaraExp) {
						String guaraacountAdress = getCountAdress(guaraExp);
						data.put("mateAcountAdress", guaraacountAdress);// 户口地址
					}
				}
			}
		}
		
		O2oMainShopInfoEntity shop = mainShopInfoService.getByLoanNo(loanapplyNo);
		if (loanUserEntity != null) {
			data.put("lonerName", loanUserEntity.getUserFullName());// 借款人
			data.put("idNumber", loanUserEntity.getDocumentNo());// 身份证号码
			data.put("mobile", loanUserEntity.getUserPhone());// 手机号
		}
		if (customerBasicInfo != null) { 
			String acountAdress = getCountAdress(customerBasicInfo);
			data.put("acountAdress", acountAdress);// 户口地址
		}

		if (shop != null) {
			data.put("licenceName", shop.getLicenceName());// 营业执照名字
			data.put("blrNumber", shop.getBlrNumber());// 营业执照注册号
			data.put("mainShopAdd", getShopeJZAdress(shop));// 营业执照地址
			data.put("controllername", loanUserEntity.getUserFullName());// 借款人
			data.put("controllerIdnum", loanUserEntity.getDocumentNo());// 身份证号码
			data.put("controllerMobile", loanUserEntity.getUserPhone());// 手机号
		}

		if (loanapply != null) {
			if (!"".equals(loanapply.getEaMount()) && loanapply.getEaMount() != null) {
				String bankAmountBigWrite = MoneyUtil
						.toChinese(formatComma2BigDecimal(loanapply.getEaMount(),2).toString());
				System.out.println(bankAmountBigWrite);

				data.put("bankAmountBigWrite", bankAmountBigWrite);// 银行批复金额大写

				data.put("bankAmountBigWrite-2", bankAmountBigWrite.substring(0, bankAmountBigWrite.length() - 2));// 银行复批金额大写去‘元整’

				data.put("loanAmount", "￥" + formatComma2BigDecimal(loanapply.getEaMount(),2));// 申请金额万元

				data.put("bankAmount", nf.format(formatComma2BigDecimal(loanapply.getEaMount(),2)));// 银行批复金额小写

				data.put("bankAmount2", "￥" + nf.format(formatComma2BigDecimal(loanapply.getEaMount(),2)));// 银行批复金额小写有￥号
			}

			data.put("loanTerm", loanapply.getLoanTerm());// 借款期限
			data.put("billCode", "浦发银行-合-" + loanapply.getBillCode());// 合作协议书编号
			if (loanapply.getRisk() != null) {
				BigDecimal saferate = loanapply.getRisk().multiply(new BigDecimal(100));
				NumberFormat nf11 = new DecimalFormat(",###.0000");
				data.put("saferate", nf11.format(formatComma2BigDecimal(saferate,4)));// 风险补偿金费率
			}
		}
		return data;
	}
	
	
	private Map<String, Object> fillZLData(String loanapplyNo) { //中旅银行、浦发广州分行
		Map<String, Object> data = new HashMap<>();
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		NumberFormat nf = new DecimalFormat(",###.00");
		if (loanapply == null) {
			return data;
		}
		
		
		
		data.put("image", getImageStr("/wordTemplate/zl.png"));//图片文件	
		
		O2oLoanUserEntity loanUserEntity = loanUserService.findById(loanapply.getLoanId(), loanapplyNo);
		if(loanapply.getEaMount().compareTo(new BigDecimal(500000.00))==1){
			data.put("payway", "2");
			data.put("receiveBank", "");// 开户行全称
			data.put("bankAccount", "");// 银行卡号
			data.put("lonerNamehm", "");// 户名
		}else{
			data.put("payway", "1");
			if (loanUserEntity != null) {
				data.put("lonerNamehm", loanUserEntity.getUserFullName());// 户名
			}
			data.put("receiveBank", loanapply.getReceiveBank());// 开户行全称
			data.put("bankAccount", loanapply.getBankAccount());// 银行卡号
		}
		
		data.put("repayMentway", o2oPubDdItemService.findPubdditemNameByCode("OTOREPAYMENTWAY", loanapply.getRepayMentway()));// 还款方式
		
		CustomerBasicInfo customerBasicInfo = loanService.getCustomerEntityById(loanUserEntity.getId());
		O2oLoanUserEntity loanSpouseUserEntity = loanUserService.findSpouseId(loanUserEntity.getLoanId(), loanapplyNo);
		List<O2oLoanUserEntity> guarantorByGuaraList = loanUserService.queryDBsById(loanapplyNo);
		O2oLoanUserEntity guarantorByGuara = null;

		if (guarantorByGuaraList != null && guarantorByGuaraList.size() > 0) {
			if (loanSpouseUserEntity == null && guarantorByGuaraList.size() > 2) {
				guarantorByGuara = guarantorByGuaraList.get(1);
			} else if (loanSpouseUserEntity != null) {
				guarantorByGuara = guarantorByGuaraList.get(0);
			}
			if (guarantorByGuara != null) {
				data.put("guarByGuara", guarantorByGuara.getUserFullName());// 担保人(用于责任担保书-第三方担保人版)
				data.put("guarIdCardByGuara", guarantorByGuara.getDocumentNo());// 担保人身份证(用于责任担保书-第三方担保人版)
				data.put("guarMobileByGuara", guarantorByGuara.getUserPhone());// 担保人电话号码(用于责任担保书-第三方担保人版)
				data.put("mateSign", "");// 配偶符号
				data.put("mateMessage", "");// 配偶丙方一通知
				CustomerBasicInfo guaraExp = loanService.getCustomerEntityById(guarantorByGuara.getId());
				if (null != guaraExp) {
					String guaraacountAdress = getCountAdress(guaraExp);
					data.put("guarAcountAdress", guaraacountAdress);// 户口地址
				}else{
					String acountAdress = getCountAdress(customerBasicInfo);
					data.put("guarAcountAdress", acountAdress);// 借款人地址
				}
			}
		} else {
			data.put("mateSign", "");// 配偶符号
			data.put("mateMessage", "");// 配偶丙方一通知
			data.put("guarByGuara", "");// 担保人
			data.put("guarIdCardByGuara", "");// 担保人身份证
		}

		if (loanSpouseUserEntity != null) {
			data.put("mateName", loanSpouseUserEntity.getUserFullName());// 配偶
			data.put("mateIdCard", loanSpouseUserEntity.getDocumentNo());// 配偶身份证
			data.put("mateMobile", loanSpouseUserEntity.getUserPhone());// 配偶手机号
			data.put("mateSign", "（配偶）");// 配偶符号
			data.put("mateMessage", "丙方一知悉并认可甲方申请的上述贷款用于夫妻共同经营。");// 配偶丙方一通知
			data.put("matebir", StringUtils.substring(loanSpouseUserEntity.getDocumentNo(), 6, 4)+"-"+StringUtils.substring(loanSpouseUserEntity.getDocumentNo(), 10, 2)+"-"+StringUtils.substring(loanSpouseUserEntity.getDocumentNo(), 12, 2));// 生日
			CustomerBasicInfo mateBasicInfo = loanService.getCustomerEntityById(loanSpouseUserEntity.getId());
			if (mateBasicInfo != null) {
				String acountAdress = getCountAdress(mateBasicInfo);
				data.put("mateAcountAdress", acountAdress);// 户口地址
			}
		} else {
			if (guarantorByGuaraList != null && guarantorByGuaraList.size() > 0) {
				guarantorByGuara = guarantorByGuaraList.get(0);
				if (guarantorByGuara != null) {
					data.put("mateName", guarantorByGuara.getUserFullName());// 担保人
					data.put("mateIdCard", guarantorByGuara.getDocumentNo());// 担保人身份证
					data.put("mateMobile", guarantorByGuara.getUserPhone());// 担保人手机号
					data.put("mateSign", "");// 配偶符号
					data.put("mateMessage", "");// 配偶丙方一通知
					CustomerBasicInfo guaraExp = loanService.getCustomerEntityById(guarantorByGuara.getId());
					if (null != guaraExp) {
						String guaraacountAdress = getCountAdress(guaraExp);
						data.put("mateAcountAdress", guaraacountAdress);// 户口地址
					}
				}
			}
		}
		O2oMainShopInfoEntity shop = mainShopInfoService.getByLoanNo(loanapplyNo);

		if (loanUserEntity != null) {
			data.put("lonerName", loanUserEntity.getUserFullName());// 借款人
			data.put("idNumber", loanUserEntity.getDocumentNo());// 身份证号码
			if(loanUserEntity.getDocumentNo()!=null && loanUserEntity.getDocumentNo().length()>14){
				data.put("lonerbirYear", loanUserEntity.getDocumentNo().substring(6,10));// 生日年
				data.put("lonerbirMonth", loanUserEntity.getDocumentNo().substring(10,12));// 生日月
				data.put("lonerbirDay", loanUserEntity.getDocumentNo().substring(12,14));// 生日日
				data.put("lonerbir", loanUserEntity.getDocumentNo().substring(6,10)+"-"+loanUserEntity.getDocumentNo().substring( 10,12)+"-"+loanUserEntity.getDocumentNo().substring(12,14));// 生日
			}
			data.put("mobile", loanUserEntity.getUserPhone());// 手机号
			data.put("sex", o2oPubDdItemService.findPubdditemNameByCode("SEX", loanUserEntity.getSex()));// 性别
		}
		if (customerBasicInfo != null) {
			
			if(customerBasicInfo.getMaritalStatus()==1){//婚姻情况:1-未婚，2-已婚,3-离异
				data.put("MarS", "未婚");// 婚姻状况
			}else if (customerBasicInfo.getMaritalStatus()==2){
				data.put("MarS", "已婚");// 婚姻状况
			}else if (customerBasicInfo.getMaritalStatus()==3){
				data.put("MarS", "离异");// 婚姻状况
			}else if (customerBasicInfo.getMaritalStatus()==4){
				data.put("MarS", "丧偶");// 婚姻状况
			}else{
				data.put("MarS", "未婚");// 婚姻状况
			}
			
			if (StringUtil.isNotBlank(customerBasicInfo.getAccountProvince())) {
				PubDditem p = pubDditemService.queryPubDditemCRM("9", customerBasicInfo.getAccountProvince());
				if (p != null) {
					data.put("lPro", p.getItemName());// 省
				}
			}

			if (StringUtil.isNotBlank(customerBasicInfo.getAccountCity())) {
				PubDditem p = pubDditemService.queryPubDditemCRM("10", customerBasicInfo.getAccountCity());
				if (p != null) {
					data.put("lc", p.getItemName());// 市
				}
			}
			String acountAdress = getCountAdress(customerBasicInfo);
			data.put("acountAdress", acountAdress);// 户口地址
			String recipientAdress = getCountJZAdress(customerBasicInfo);
			data.put("recipientAdress", recipientAdress);// 居住地址
		}

		if (shop != null) {
			data.put("SCY", DateUtils.getYear(shop.getStupdate()));// 年
			data.put("SCM", DateUtils.getMonth(shop.getStupdate())+1);// 月
			data.put("businesshours", shop.getBusinesshours());//营业时间
			data.put("licenceName", shop.getLicenceName());// 营业执照名字
			data.put("blrNumber", shop.getBlrNumber());// 营业执照注册号
			data.put("mainShopAdd", getShopeJZAdress(shop));// 营业执照地址
			data.put("controllername", loanUserEntity.getUserFullName());// 借款人
			data.put("controllerIdnum", loanUserEntity.getDocumentNo());// 身份证号码
			data.put("controllerMobile", loanUserEntity.getUserPhone());// 手机号
			
		}

		if (loanapply != null) {
			if (!"".equals(loanapply.getEaMount()) && loanapply.getEaMount() != null) {
				String bankAmountBigWrite = MoneyUtil
						.toChinese(formatComma2BigDecimal(loanapply.getEaMount(),2).toString());
				System.out.println(bankAmountBigWrite);

				data.put("bankAmountBigWrite", bankAmountBigWrite);// 银行批复金额大写

				data.put("bankAmountBigWrite_2", bankAmountBigWrite.substring(0, bankAmountBigWrite.length() - 2));// 银行复批金额大写去‘元整’

				data.put("loanAmount", "￥" + formatComma2BigDecimal(loanapply.getEaMount(),2));// 申请金额万元

				data.put("bankAmount", nf.format(formatComma2BigDecimal(loanapply.getEaMount(),2)));// 银行批复金额小写

				data.put("bankAmount2", "￥" + nf.format(formatComma2BigDecimal(loanapply.getEaMount(),2)));// 银行批复金额小写有￥号
			}

			data.put("loanTerm", loanapply.getLoanTerm());// 借款期限
			
			if("SPDBGZ".equals(loanapply.getBankLoanName())){
				data.put("billCode", "浦发广州分行-合-" + loanapply.getBillCode());// 合作协议书编号
			}else{
				data.put("billCode", "中旅银行-合-" + loanapply.getBillCode());// 合作协议书编号
			}
			if (loanapply.getRisk() != null) {
				BigDecimal saferate = loanapply.getRisk().multiply(new BigDecimal(100));
				NumberFormat nf11 = new DecimalFormat(",###.0000");
				data.put("saferate", nf11.format(formatComma2BigDecimal(saferate,4)));// 风险补偿金费率
			}
		}
		return data;
	}

	private boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			if (value.contains("."))
				return true;
			return false;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	private boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	private boolean isNumber(String value) {
		return isInteger(value) || isDouble(value);
	}

	private BigDecimal formatComma2BigDecimal(Object obj,int num) {
		String val = String.valueOf(obj);
		if (val == null)
			return new BigDecimal("0.00");

		val = val.replaceAll(",", "");
		if (!isNumber(val))
			return new BigDecimal("0.00");

		BigDecimal decimal = new BigDecimal(val);
		decimal = decimal.setScale(num, BigDecimal.ROUND_UP);

		return decimal;

	}

	private String getCountAdress(CustomerBasicInfo basic) { //户口所在地
		String acountAdress = "";
		if (StringUtil.isNotBlank(basic.getAccountProvince())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("9", basic.getAccountProvince());
			if (p != null) {
				acountAdress = acountAdress + p.getItemName();
			}
		}

		if (StringUtil.isNotBlank(basic.getAccountCity())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("10", basic.getAccountCity());
			if (p != null) {
				acountAdress = acountAdress + p.getItemName();
			}
		}

		if (StringUtil.isNotBlank(basic.getAccountAounty())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("11", basic.getAccountAounty());
			if (p != null) {
				acountAdress = acountAdress + p.getItemName();
			}
		}

		if (basic.getPermanentresidence() != null) {
			acountAdress = acountAdress + basic.getPermanentresidence();
		}
		return acountAdress;

	}
	
	private String getCountJZAdress(CustomerBasicInfo basic) {//居住地址
		String acountAdress = "";
		if (StringUtil.isNotBlank(basic.getRecipientProvince())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("9", basic.getRecipientProvince());
			if (p != null) {
				acountAdress = acountAdress + p.getItemName();
			}
		}

		if (StringUtil.isNotBlank(basic.getRecipientCity())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("10", basic.getRecipientCity());
			if (p != null) {
				acountAdress = acountAdress + p.getItemName();
			}
		}

		/*if (StringUtil.isNotBlank(basic.getRecipientCounty())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("11", basic.getRecipientCounty());
			if (p != null) {
				acountAdress = acountAdress + p.getItemName();
			}
		}

		if (basic.getRecipientAddress() != null) {
			acountAdress = acountAdress + basic.getRecipientAddress();
		}*/
		return acountAdress;

	}
	
	/**
	 * @Title: getShopeJZAdress
	 * @Description: 查询营业执照地址
	 * @author 张庆奇
	 * @param shop
	 * @return
	 * @return String
	 * @throws
	 * @date 2017年11月7日 下午3:38:05
	 */
	private String getShopeJZAdress(O2oMainShopInfoEntity shop) {//门店地址
		String shopaddress = "";
		if (StringUtil.isNotBlank(shop.getShopprovince())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("9", shop.getShopprovince());
			if (p != null) {
				shopaddress = shopaddress + p.getItemName();
			}
		}

		if (StringUtil.isNotBlank(shop.getShopcity())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("10", shop.getShopcity());
			if (p != null) {
				shopaddress = shopaddress + p.getItemName();
			}
		}

		if (StringUtil.isNotBlank(shop.getShopcounty())) {
			PubDditem p = pubDditemService.queryPubDditemCRM("11", shop.getShopcounty());
			if (p != null) {
				shopaddress = shopaddress + p.getItemName();
			}
		}

		if (shop.getShopaddress() != null) {
			shopaddress = shopaddress + shop.getShopaddress();
		}
		return shopaddress;

	}
	
	public String getImageStr(String imgFile) {  
        InputStream in = null;  
        byte[] data = null;  
        String path =  SPDBGZContractRestContorller.class.getResource("/").getPath();
        try {  
            in = new FileInputStream(path+imgFile);  
            data = new byte[in.available()];  
            in.read(data);  
            in.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return Base64.encodeBase64String(data);  
    }  
	
	
}
